<?php

namespace app\ports\controller;

use app\ports\constants\TeamsConstants;
use app\ports\controller\publics\DataSql;
use app\ports\controller\publics\Teams;
use app\ports\controller\publics\Template;
use think\Db;

/**
 * 达标计算
 * Class
 * @package
 */
class Stands
{
	use \app\common\traits\ToolTrait;
	/**
	 * 分红人员 达标计算 入口
	 */
	public function bonus_person_stands_cals()
	{
		try {
			$limit = 20;
			$month  = date("Y-m", strtotime("-1 month", time()));
			$pageArr = ["total" => 0, "page" => 0, "times" => ""];
			$path = "./timer/bonus/stands";
			$file = $path . "/person_stands.txt";
			$isDir = $this->creDirectory($path);
			if ($isDir) {
				if (!file_exists($file)) file_put_contents($file, serialize($pageArr));
			}
			$flag = true;
			$page_info = unserialize(file_get_contents($file));
			if ($page_info) {
				$total = 0;
				$now_times = strtotime(date("Y-m", time()));
				if (isset($page_info["total"]) && empty($page_info["total"])) {
					$pageArr["times"] = $month;
					$con = $this->_user_con($month);
					if (!empty($page_info["times"])) {
						$times = date("Y-m", strtotime("+1 month", strtotime($page_info["times"])));
						if ($now_times > strtotime($times)) {
							$pageArr["times"] = $times;
							$this->_user_con($times);
						} else {
							$flag = false;
						}
					}
					if ($flag) {
						$con && $total = (int)ceil($con / $limit);
						$pageArr["total"] = $total;
						file_put_contents($file, serialize($pageArr));
					}
				} else {
					if ($page_info["total"] == $page_info["page"]) {
						$times = date("Y-m", strtotime("+1 month", strtotime($page_info["times"])));
						if ($now_times > strtotime($times)) {
							// 更新翻页信息
							$pageArr["times"] = $times;
							$con =   $this->_user_con($pageArr["times"]);
							$con && $total = (int)ceil($con / $limit);
							$pageArr["total"] = $total;
							file_put_contents($file, serialize($pageArr));
						} else {
							$flag = false;
						}
					}
				}
			}
			if ($flag) {
				$pageRes = unserialize(file_get_contents($file));
				$page = $pageRes["page"] + 1;
				$offset = ($page - 1) * $limit;
				$query = Db::name("user")
					->field("id")
					->where("ptype = 2 and jointime < " . strtotime("+1 month", strtotime($pageRes["times"])))
					->limit((int)$offset, (int)$limit)
					->select();
				if ($query) {
					$ch = false;
					for ($i = 0; $i < count($query); $i++) {
						$res = Teams::instance($month)->calc_able_personnel($query[$i]["id"]);
						if ($res) {
							$this->_trans_calc_stands($query[$i]["id"], $month);
						}
						$ch = true;
					}
					if ($ch) {
						$pageRes["page"] = $page;
						file_put_contents($file, serialize($pageRes));
					}
				}
			}
		} catch (\Exception $e) {
			$this->logs("./portsLogs/bonus", "person_stands_" . date("Y-m") . ".txt", [$e->getMessage()]);
		}
	}

	/**
	 * 会员人数
	 */
	protected function _user_con($times)
	{
		return Db::name("user")
			->where("ptype = 2 and jointime < " . strtotime("+1 month", strtotime($times)))
			->count();
	}

	/**
	 * 达标交易计算
	 * @param  $pid 达标计算代理ID
	 * @param  $times 计算时间
	 */
	protected function _trans_calc_stands($pid, $times)
	{
		$responce =  Teams::instance($times)->_all_direct_level($pid);
		if ($responce) {
			$stands = [];
			$standsMoney = bcmul(TeamsConstants::DEFAULT_STANDS_MONEY, '10000', 2);
			foreach ($responce as $key => $vals) {
				$teams = Teams::instance($times)->_all_Lower_Level_teams_ids($vals["id"]);
				$teams = array_merge($teams, [$vals["id"]]);
				$imp = implode(",", $teams);
				$transAmt = $this->_trans($imp, $times);
				if ($transAmt >= $standsMoney) {
					$temp = [];
					$temp = ["childs" => $vals["id"], "money" => $transAmt];
					array_push($stands, $temp);
				}
			}
			if (count($stands) >= TeamsConstants::DEFAULT_STANDS_NUMS) {
				$this->_stands_upgrade($pid, $stands, $times);
			}
		}
	}

	/**
	 * 达标晋级
	 * @param  $pid 达标计算代理ID
	 * @param  $times 计算时间
	 * @param  $data  交易数据
	 */
	protected function _stands_upgrade($pid, $data, $times)
	{
		if (!empty($data)) {
			$con = count($data);
			$temps = Template::instance()->stands_calc($con);
			if ($temps) {
				$tmp = [];
				foreach ($temps as $val) {
					$i = 0;
					foreach ($data as  $v) {
						if ($val["money"] <= $v["money"]) $i++;
					}
					$tmp[$val["code"]] = $i;
				}
				if ($tmp) {
					// 匹配达标模板
					foreach ($tmp as $k => $v) {
						$check = Template::instance()->_check_use_stands($k, $v);
						if ($check) {
							$this->_store_upgrade_cords($k, $pid, $times, $data);
						}
					}
				}
			}
		}
	}

	/**
	 * 存储晋级记录
	 * @param  $id  等级ID
	 * @param  $pid 达标计算代理ID
	 * @param  $times 计算时间
	 * @param  $data  交易数据
	 */
	protected function _store_upgrade_cords($lev_code, $pid, $times, $data)
	{
		if (!empty($lev_code) && !empty($pid) && !empty($times) && !empty($data)) {
			$times = strtotime($times);
			$option = [
				"agid"		=> $pid,
				"lev_code"	=> $lev_code,
				"times"		=> $times
			];
			$check = Db::name("bonus_upgrade")->where($option)->count();
			if (!$check) {
				$option["stands"] = json_encode($data);
				$option["createTime"] = time();
				Db::name("bonus_upgrade")->insert($option);
			}
		}
	}

	/**
	 * 获取交易
	 * @param  string $ids  所有下级ID
	 * @param  string $times 计算时间
	 */
	protected function _trans(string $ids, string $times)
	{
		$sum = 0;
		if (!empty($ids) && !empty($times)) {
			$table = "fd_bonus_calc_trans_" . date("Y", strtotime($times));
			$sum  = Db::table($table)->where("agid in ({$ids}) and times = " . strtotime($times))->sum("transAmt");
		}
		return $sum;
	}
}
